#include "PackagedTask.h"
#include "Async/Async.h"
#include "Containers/Vector.h"

void WH::BlockUntilFinished(std::shared_ptr<CPackagedTaskBase> InPackagedTask)
{
    assert(CAsyncSystem::IsInMainThread()&&"this function cant run in worker thread");

    //cant block a started task,because it might already finished
    //,and its NextTask will be auto set none
    //to make sure whole task chain will be finished
    //we need to make sure all task in chain is not started
    assert(!InPackagedTask->IsStarted() && "cant block a started task");


    TVector<TThreadSafeSharedPtr<CTaskBase>> TaskStack;
    for(auto CurrentTask=InPackagedTask->GetLowLevel();CurrentTask;CurrentTask=CurrentTask->NextTask)
    {
        TaskStack.Add(CurrentTask);
    }

    InPackagedTask->Start();

    int i=0;
    while(i<TaskStack.Num())
    {
        TThreadSafeSharedPtr<CTaskBase> CurrentTask=TaskStack[i];

        if(CurrentTask->IsFailed())
        {
            //return because faile
            return;
        }

        if(CurrentTask->IsFinished())
        {
            i++;
            continue;
        }

        //incase the tast is mainthread task
        CAsyncSystem::Get()->DoMainThreadWork();
    }
}